import { Button, message, Modal, Tag, Upload } from 'antd';
import * as XLSX from 'xlsx';
const { Dragger } = Upload;

import ProTable from '@ant-design/pro-table';
import { useEffect, useState } from 'react';
import type { UploadExcelProps } from './data';
const UploadFile: React.FC<UploadExcelProps> = (props, uploadRef) => {
  //   state = {
  //     tableData: [],
  //     tableHeader: [],
  //   };

  const [tableData, setTableData] = useState([]);
  const [tableHeader, setTableHeader] = useState([]);
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  // const [errorStatus, setErrorStatus] = useState(false);

  useEffect(() => {
    setVisible(props.visible);
    const temp = props.tableHeader.filter((item) => item.title !== '操作');
    if (props.errorStatus) {
      temp.push({
        title: '错误信息',
        align: 'center',
        sorter: true,
        dataIndex: 'errorMsg',
        fixed: 'right',
        render: (text, record, _, action) => {
          console.log(text);
          return <Tag color={'red'}>{text}</Tag>;
        },
      });
    }

    setTableHeader(temp || []);
  }, [props.visible, props.tableHeader]);

  //   toReturn = () => {
  //     this.props.close();
  //   };

  //   toSubmit = () => {
  //     const _this = this;
  //     this.props.submit(_this.state.tableData);
  //   };
  const uploadFilesChange = (file) => {
    // 通过FileReader对象读取文件
    const fileReader = new FileReader();
    // 以二进制方式打开文件
    fileReader.readAsBinaryString(file.file);
    fileReader.onload = (event) => {
      try {
        const { result } = event.target;
        // 以二进制流方式读取得到整份excel表格对象
        const workbook = XLSX.read(result, { type: 'binary' });
        // 存储获取到的数据
        const data = {};
        // 遍历每张工作表进行读取（这里默认只读取第一张表）
        for (const sheet in workbook.Sheets) {
          const tempData = [];
          // esline-disable-next-line
          if (workbook.Sheets.hasOwnProperty(sheet)) {
            // 利用 sheet_to_json 方法将 excel 转成 json 数据
            console.log(sheet);
            // for (const item in props.tableHeader) {
            //   if(times.)
            // }
            data[sheet] = tempData.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
          }
        }
        const excelData = data.Sheet1;
        console.log(excelData, '---excelData--');
        const excelHeader = [];
        // 获取表头
        for (const headerAttr in excelData[0]) {
          // if (props.headMap === null || props.headMap === undefined) {
          const header = {
            title: headerAttr,
            dataIndex: headerAttr,
            key: headerAttr,
          };
          // } else {
          //   if (
          //     props.headMap?.get(headerAttr) == null ||
          //     props.headMap?.get(headerAttr) == undefined
          //   ) {
          //     header = {
          //       title: headerAttr,
          //       dataIndex: headerAttr,
          //       key: headerAttr,
          //     };
          //   } else {
          //     header = {
          //       title: headerAttr,
          //       dataIndex: props.headMap?.get(headerAttr),
          //       key: headerAttr,
          //     };
          //   }
          // }

          excelHeader.push(header);
        }
        // 最终获取到并且格式化后的 json 数据
        console.log(excelData, '--excelData--');
        excelData.map((item) => (item.id = (Math.random() * 1000000).toFixed(0)));
        // setTableHeader(excelHeader);
        setTableData(excelData);
        // this.setState({
        //   tableData: excelData,
        //   tableHeader: excelHeader,
        // });
      } catch (e) {
        // 这里可以抛出文件类型错误不正确的相关提示
        console.log(e);
        message.error('文件类型不正确！');
      }
    };
  };

  return (
    <div>
      <Modal
        width={1000}
        height="93%"
        wrapClassName="modal"
        className="modal-add-content"
        title={props.title}
        okButtonProps={{ loading: loading }}
        visible={visible}
        onCancel={() => {
          props.onCancel();
        }}
        // onOk={async () => {
        //   setLoading(true);
        //   props.onOk();
        //   setLoading(false);
        // }}
        destroyOnClose={true}
        footer={null}
      >
        <Dragger
          name="file"
          accept=".xls,.xlsx"
          maxCount={1}
          beforeUpload={function () {
            return false;
          }}
          onChange={uploadFilesChange}
          showUploadList={false}
        >
          <p className="ant-upload-text">
            <span>点击上传文件</span>
            或者拖拽上传
          </p>
        </Dragger>
        <ProTable
          search={false}
          options={false}
          columns={tableHeader}
          scroll={{ x: 6000 }}
          dataSource={tableData}
          style={{ marginTop: '20px' }}
          // recordCreatorProps={{
          //   record: () => {
          //     return {
          //       id: `0${Date.now()}`,
          //     };
          //   },
          // }}
          rowKey="id"
          pagination={false}
        />
        <div style={{ textAlign: 'center', marginTop: '20px' }}>
          <Button
            onClick={() => {
              props.onCancel();
            }}
          >
            返回
          </Button>
          <Button
            onClick={() => {
              const result = props.onCheck(tableData);
              console.log(result);
              setTableData(result);
            }}
          >
            校验按钮
          </Button>
          <Button
            style={{ marginLeft: '25px' }}
            onClick={async () => {
              setLoading(true);
              props.onOk(tableData, tableHeader);
              setLoading(false);
            }}
            className="addbutton"
            type="primary"
          >
            确认
          </Button>
        </div>
      </Modal>
    </div>
  );
};

export default UploadFile;
